package com.zhangln.mountbuzhou.service;

import com.zhangln.mountbuzhou.dao.TbAuthDao;
import com.zhangln.mountbuzhou.dto.BaseResponse;
import com.zhangln.mountbuzhou.dto.ResultCode;
import com.zhangln.mountbuzhou.entity.TbAuthEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author sherry
 * @description
 * @date Create in 2020/4/27
 * @modified By:
 */
@Service
@Slf4j
public class AuthService {

    @Value("${buzhou.auth.timeout:10}")
    private Integer timeout;

    private final TbAuthDao tbAuthDao;
    private final RedisTemplate redisTemplate;

    public AuthService(TbAuthDao tbAuthDao, RedisTemplate redisTemplate) {
        this.tbAuthDao = tbAuthDao;
        this.redisTemplate = redisTemplate;
    }

    public BaseResponse getToken(String username, String password) {
        log.info("对  {},{} 执行获取token操作", username, password);
        TbAuthEntity tbAuthEntity = tbAuthDao.getAuthByUsername(username);
        if (tbAuthEntity != null && Objects.equals(password, tbAuthEntity.getPassword())) {
            Object tokenInRedis = redisTemplate.opsForValue().get("TOKEN_USERNAME:" + username);
            log.info("当前用户名在Redis中存储的token为：{}", tokenInRedis);
            String token = tokenInRedis == null ? UUID.randomUUID().toString() : String.valueOf(tokenInRedis);
            redisTemplate.opsForValue().set("TOKEN:" + token, tbAuthEntity, timeout, TimeUnit.MINUTES);
            redisTemplate.opsForValue().set("TOKEN_USERNAME:" + username, token, timeout, TimeUnit.MINUTES);
            return BaseResponse.builder().data(token).build();
        } else {
            return BaseResponse.builder().code(ResultCode.UN_AUTHORIZED).data("token获取失败").build();
        }
    }

    /**
     * 校验token
     *
     * @param token
     * @return
     */
    public BaseResponse checkToken(String token) {
        log.info("对 token：{} 进行校验", token);
//        开发时可以用
        if (Objects.equals(token, "123456")) {
            return BaseResponse.builder().code(ResultCode.SUCCESS).build();
        }

        Object o = redisTemplate.opsForValue().get("TOKEN:" + token);
        if (o != null) {
            log.info("{} 校验通过", token);
            return BaseResponse.builder().code(ResultCode.SUCCESS).build();
        }
        return BaseResponse.builder().code(ResultCode.FAILURE).build();
    }
}
